var ws = require("nodejs-websocket");
console.log("开始建立连接...")
var WebSocket = require('ws')
const moment = require('moment');
const pako = require('pako');
const axios = require('axios');

var game1 = null,
    game2 = null,
    game1Ready = false,
    game2Ready = false;

var orderbook = {};

exports.OrderBook = orderbook;
WS_URL = 'wss://api.huobi.br.com/ws';
var server = ws.createServer(function (conn) {
    conn.on("text", function (str) {
        console.log("收到的信息为:" + str)
        // if (str === "ethusdt") {
        game1 = conn;
        game1Ready = true;
        conn.sendText("success");
        function subscribe(ws) {
            var symbols = ['btcusdt'];
            // 订阅K线
            for (let symbol of symbols) {

                ws2.send(JSON.stringify({
                    "req": `market.${symbol}.kline.1min`,
                    "id": `${symbol}`,
                }));
            }
        }
        // }

        function handle(data) {
            console.log('received', data.ch, 'data.ts', data.ts, 'crawler.ts', moment().format('x'));
            let symbol = data.ch.split('.')[1];
            let channel = data.ch.split('.')[2];
            switch (channel) {
                case 'depth':
                    orderbook[symbol] = data.tick;
                    console.log(data.tick);
                    break;
                case 'kline':
                    console.log('kline', data.tick);
                    break;
            }
        }
        var ws2 = new WebSocket(WS_URL);
        ws2.on('open', () => {
            console.log('open');
            subscribe(ws);
        });
        ws2.on('message', (data) => {
            let text = pako.inflate(data, {
                to: 'string'
            });
            let msg = JSON.parse(text);
            if (msg.ping) {
                console.log(msg);
                ws2.send(JSON.stringify({
                    pong: msg.ping
                }));
            } else if (msg.tick) {

                handle(msg);
            } else {
                if(str === 'history') {
                    let url = 'http://chen.test/api/admin/ticks/btcusdt_history';
                    axios.post(url, {
                        message: JSON.parse(text)
                    })
                        .then(function (response) {
                            console.log(response);
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                    // console.log(JSON.parse(text));
                    // let res = JSON.parse(text)
                    // console.log(res.data);
                    // conn.sendText(res);
                    return false;
                }
            }

        });


    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(8001)
console.log("WebSocket建立完毕")
